package com.esun.server.aspect;

import com.esun.dao.eo.BaseEo;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 修改信息切面类
 * 拦截所有Das层请求。给所有实体类加上对应的修改时间和用户和程序
 * @author John.xiao
 * @date 2021/8/16 14:20
 */
@Slf4j
//@Componentgr
@Aspect
public class CreateAndModifyAspect {

	@Around("execution(* com.esun.dao.das.*.*(..))")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		//要切面的方法
		Set<String>  methodName = Sets.newHashSet("insert","insertBatch","update","insertOrUpdateBatch");
		if (!methodName.contains(method.getName())){
			return joinPoint.proceed();
		}
		//获取参数名和参数类
		Object[] args = joinPoint.getArgs();
		//获取修改用户ID 和 修改程序名
		String modifyUser = request.getHeader("USER_ID");
		String modifyProgram = request.getHeader("PROGRAM");
		//赋值
		for (Object object : args){
			if (object == null){
				continue;
			}
			//如果为list则为全部元素赋值
			if (object instanceof List){
				List<?> list = (List<?>) object;
				if (CollectionUtils.isNotEmpty(list)){
					for (Object listObject : list){
						 if (listObject instanceof BaseEo){
						 	BaseEo baseEo = (BaseEo) listObject;
						 	baseEo.setModifyDatetime(LocalDateTime.now());
						 	baseEo.setModifyUser(modifyUser);
						 	baseEo.setModifyProgram(modifyProgram);
						 }
					}
				}
			}
			if (object instanceof  BaseEo){
				BaseEo baseEo = (BaseEo) object;
				baseEo.setModifyDatetime(LocalDateTime.now());
				baseEo.setModifyUser(modifyUser);
				baseEo.setModifyProgram(modifyProgram);
			}
		}
		return joinPoint.proceed();
	}
}
